package com.cvtt.common;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import android.util.Log;


public class AESUtil {
	public static final String AES_VECTOR = "734E54E608E8D616";
	public static final String AES_KEY = "4D31BA600257A163";

	/**
	 * 自定义填充
	 * */
	private static byte[] fillDataZero(String data) {
		byte[] dataStr = data.getBytes();
		int data_length = dataStr.length;
		int endata_length = data_length;
		if ((data_length % 16) == 0)
			endata_length = data_length;
		else
			endata_length = data_length + (16 - (dataStr.length % 16));

		byte[] dataStr2 = new byte[endata_length];

		for (int i = 0; i < endata_length; i++)
			dataStr2[i] = 0;

		for (int i = 0; i < data_length; i++)
			dataStr2[i] = dataStr[i];
		return dataStr2;
	}

	private static String byte2String(byte[] data) {
		int len = data.length;//cz chang 原来是0，2015-11-20
		for (int i = 0; i < data.length; i++) {
			if (data[i] == 0) {
				len = i;
				break;
			}
		}
		byte[] dataStr = new byte[len];

		for (int i = 0; i < len; i++) {
			dataStr[i] = data[i];
		}

		String originalString = new String(dataStr);
		return originalString;
	}

	/**
	 * 加密
	 * 
	 * @param content
	 *            加密内容
	 * @param sKey
	 *            密钥
	 * @param vetor
	 *            向量
	 * @return
	 * @throws Exception
	 */
	public static String Encrypt(String content, String sKey, String vetor) throws Exception {

		SecretKeySpec skeySpec = new SecretKeySpec(sKey.getBytes(), "AES");
		Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
		IvParameterSpec iv = new IvParameterSpec(vetor.getBytes());
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
		byte[] byteContent = fillDataZero(content);
		byte[] encrypted = cipher.doFinal(byteContent);
		return Base64.encodeBytes(parseByte2HexStr(encrypted).getBytes());
	}

	/**
	 * 解密
	 * 
	 * @param content
	 *            加密内容
	 * @param sKey
	 *            密钥
	 * @param vetor
	 *            向量
	 * @return
	 * @throws Exception
	 */
	
//	public static String decodeAES(String content, String sKey, String vetor, boolean flag) {
//
//		try {
//			SecretKeySpec skeySpec = new SecretKeySpec(sKey.getBytes(), "AES");
//			Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
//			IvParameterSpec iv = new IvParameterSpec(vetor.getBytes());
//			cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
//			byte[] encrypted1 = Base64.decode(content);
//			byte[] original = cipher.doFinal(parseHexStr2Byte(new String(encrypted1, "ISO-8859-1")));
//			String originalString = "";
//			if (flag) {
//				originalString = new String(original, "ISO-8859-1");
//			}
//			else {
//				originalString = byte2String(original);
//			}
//			return originalString;
//		}
//		catch (Exception ex) {
//			return "";
//		}
//
//	}

	public static String decodeAES(String content, String sKey, String vetor, boolean flag) {

		try {
			SecretKeySpec skeySpec = new SecretKeySpec(sKey.getBytes(), "AES");
			Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
			IvParameterSpec iv = new IvParameterSpec(vetor.getBytes());
			cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
			byte[] encrypted1 = Base64.decode(content);
			byte[] original = cipher.doFinal(parseHexStr2Byte(new String(encrypted1, "ISO-8859-1")));//"UTF-8"//"ISO-8859-1"
			String originalString = "";
			if (flag) {
				originalString = new String(original, "ISO-8859-1");//"UTF-8"//
			}
			else {
				originalString = byte2String(original);
			}
			return originalString;
		}
		catch (Exception ex) {
			return "";
		}

	}

	/**
	 * 将二进制转换成16进制
	 * 
	 * @param buf
	 * @return
	 */
	public static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

	/**
	 * 将16进制转换为二进制
	 * 
	 * @param hexStr
	 * @return
	 */
	public static byte[] parseHexStr2Byte(String hexStr) {
		if (hexStr.length() < 1)
			return null;
		byte[] result = new byte[hexStr.length() / 2];
		for (int i = 0; i < hexStr.length() / 2; i++) {
			int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
			result[i] = (byte) (high * 16 + low);
		}
		return result;
	}
	
    public static String binaryString2hexString(String bString)  
    {  
        if (bString == null || bString.equals("") || bString.length() % 8 != 0)  
            return null;  
        StringBuffer tmp = new StringBuffer();  
        int iTmp = 0;  
        for (int i = 0; i < bString.length(); i += 4)  
        {  
            iTmp = 0;  
            for (int j = 0; j < 4; j++)  
            {  
                iTmp += Integer.parseInt(bString.substring(i + j, i + j + 1)) << (4 - j - 1);  
            }  
            tmp.append(Integer.toHexString(iTmp));  
        }  
        return tmp.toString();  
    }  
}
